﻿using System;
using System.Collections.Generic;
using Microsoft.SharePoint.Administration;

namespace TemplateLibraryConnector.Utility
{
    public class ULSLogger : SPDiagnosticsServiceBase
    {
        private const string DiagnosticAreaName = "Template Library Connector";
        private const string CategoryName = "Content Type association Timer Job";
        private static ULSLogger _current;
        
        public static ULSLogger Current
        {
            get { return _current ?? (_current = new ULSLogger()); }
        }
        private ULSLogger() : base("Template Library Connector Logging Service", SPFarm.Local)
        {
        }

        protected override IEnumerable<SPDiagnosticsArea> ProvideAreas()
        {
            var areas = new List<SPDiagnosticsArea>
            {
                new SPDiagnosticsArea(DiagnosticAreaName, 0, 0, false,
                    new List<SPDiagnosticsCategory>{ new SPDiagnosticsCategory(CategoryName, null, TraceSeverity.Unexpected, EventSeverity.Error, 0, 0, false, true ) }) };
            return areas;
        }

        public static void LogError(string errorMessage, Exception ex)
        {
            var category = ULSLogger.Current.Areas[DiagnosticAreaName].Categories[CategoryName];
            var output = string.Format("Message: {0} Additional information: {1} Source: {2} StackTrace: {3} InnerException: {4}", ex.Message, errorMessage, ex.Source, ex.StackTrace, ex.InnerException.Message);

            ULSLogger.Current.WriteTrace(0, category, TraceSeverity.Unexpected, output);
        }
        public static void LogMessage(string message)
        {
            var category = ULSLogger.Current.Areas[DiagnosticAreaName].Categories[CategoryName];
            ULSLogger.Current.WriteTrace(0, category, TraceSeverity.Medium, message);
        }
    }
}
